<template>
  <div>
    <el-row>
      <el-col
        :span="6"
        :style="{'height' : tableHeight + 'px', 'overflow': 'auto'}"
      >
        <AgencyTree
          class="agencyTree"
          @handleTreeQuery="handleTreeQuery"
        />
      </el-col>
      <el-col :span="18">
        <!-- 表格部分 -->
        <el-row style="margin-left:2%">
          <el-col :span="10">
            <span>单位列表：</span>
            <el-table
              ref="agencyTable"
              v-loading="agencyLoading"
              :data="agencyData"
              :height="tableHeight"
              :stripe="true"
              :header-cell-class-name="cellCheckbox"
              style="width: 100%"
              :header-cell-style="{background:'#eef1f6',color:'#606266'}"
              @selection-change="handleAgencySelectionChange"
              @row-click="handleAgencyRowClick"
              @select="tableSelect"
            >
              <template slot="empty">
                <tableEmpty />
              </template>
              <el-table-column
                type="selection"
                width="50"
              />
              <el-table-column
                type="index"
                label="序号"
                width="50"
              />
              <el-table-column
                prop="agencyCode"
                label="单位编码"
                width="120"
              />
              <el-table-column
                prop="agencyName"
                label="单位名称"
              />
            </el-table>
          </el-col>
          <el-col :span="4">
            <div style="margin-top: 80%; margin-left: 20%;">
              <div>
                <el-button
                  round
                  size="small"
                  type="primary"
                > 》挂接》 </el-button>
              </div>
              <!-- <div class="spacing" @click="handleRemoveSelect">
                <el-button icon="el-icon-d-arrow-left" :disabled="nowSelectRightData.length?false:true" :size="buttonSize" type="primary">
                  取消
                </el-button>
              </div> -->
            </div>
          </el-col>
          <el-col :span="10">
            <span>工资项列表：</span>
            <el-table
              ref="salaryTable"
              v-loading="salaryLoading"
              :data="salaryData"
              :height="tableHeight"
              :stripe="true"
              style="width: 100%"
              :header-cell-style="{background:'#eef1f6',color:'#606266'}"
              @selection-change="handleSalarySelectionChange"
              @row-click="handleSalaryRowClick"
            >
              <template slot="empty">
                <tableEmpty />
              </template>
              <el-table-column
                type="selection"
                width="50"
                :selectable="selectable"
              />
              <el-table-column
                type="index"
                label="序号"
                width="50"
              />
              <!-- <el-table-column
                prop="salaryCode"
                label="工资项代码"
                width="120"
              /> -->
              <el-table-column
                prop="salaryName"
                label="工资项名称"
              />
            </el-table>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { queryAgencyInfo } from '@/api/unitInformationMaintenance/unitInformationEdit'
import {
  querySalaryBasedataInfo,
  saveAgencySalary,
  queryAgencySalaryInfoByAgencyId
} from '@/api/salaryConfigManage/salaryProjectConnect'
import AgencyTree from '@/components/tree/agencyTree'
import tableEmpty from '@/components/table/empty'
export default {
  name: 'AgencyConnSalaryChildren',
  components: { AgencyTree, tableEmpty },
  filters: {},
  props: ['agencyTreeData'],
  data() {
    return {
      tableHeight: null,
      listQuery: {
        page: 1,
        limit: 200,
        flag: 'all',
        agencyId: '0',
        changeAgency: '',
        salaryType: '',
        menuid: this.$router.currentRoute.meta.menuid
      },
      agencyLoading: false,
      salaryLoading: true,
      query: {
        agencyId: '0'
      },
      // treeData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      agencyData: [],
      salaryData: [],
      agencySelectData: [], // 单位表格选中数据
      salarySelectData: [] // 工资表格选中数据
    }
  },
  watch: {
    salaryData(val) {
      this.doLayout()
    },
    agencyData(val) {
      this.doLayout()
    }
  },
  mounted() {
    this.getTbHeight()
  },
  beforeMount() {
    window.addEventListener('resize', this.getTbHeight)
  },
  created() {
    // 查询工资项数据
    this.querySalaryBasedataInfo()
    // 查询单位数据
    this.getChildrenAgencyInfoById()
  },
  methods: {
    /* 重新渲染table组件 */
    doLayout() {
      this.$nextTick(() => {
        this.$refs.salaryTable.doLayout()
        this.$refs.agencyTable.doLayout()
      })
    },
    // 获取table高度的方法
    getTbHeight() {
      this.tableHeight = window.innerHeight - 220
    },
    // 树方法
    handleTreeQuery(data) {
      this.handleNodeClick(data)
    },
    handleQuery() {
      this.$refs.salaryTable.clearSelection()
      this.$refs.agencyTable.clearSelection()
      this.querySalaryBasedataInfo()
    },
    cellCheckbox(row) {
      if (row.columnIndex === 0) {
        return 'disabledCheck'
      }
    },
    // 点击树事件，查询单位表格
    handleNodeClick(data) {
      this.query.agencyId = data.id
      this.getChildrenAgencyInfoById()
    },
    // 根据id获取当前节点下的单位信息
    getChildrenAgencyInfoById() {
      this.agencyLoading = true
      queryAgencyInfo(this.query).then(respnse => {
        this.agencyData = respnse.data
        this.agencyLoading = false
      })
    },
    // 获取所有工资项表格数据
    querySalaryBasedataInfo() {
      querySalaryBasedataInfo().then(response => {
        this.salaryData = response.data
        this.salaryLoading = false
      })
    },
    // 点击单位表格行选中复选框
    handleAgencyRowClick(row) {
      // 如果当前时选中状态，在点击该数据时，取消选中
      if (this.agencySelectData.length > 0) {
        if (row.id !== this.agencySelectData[0].id) {
          this.$refs.agencyTable.clearSelection()
          this.$refs.agencyTable.toggleRowSelection(row)
        } else {
          this.$refs.agencyTable.toggleRowSelection(row)
        }
      } else {
        this.$refs.agencyTable.toggleRowSelection(row)
      }
    },
    // 点击工资项表格行选中复选框
    handleSalaryRowClick(row) {
      if (
        row.salaryCode !== 's1' &&
        row.salaryCode !== 's2'
      ) {
        this.$refs.salaryTable.toggleRowSelection(row)
      }
    },
    tableSelect(row) {
      if (this.agencySelectData.length > 0) {
        for (let i = 0; i < row.length; i++) {
          if (row[i].id !== this.agencySelectData[0].id) {
            // 获取表格选中数据。 如果和当前不一致，取消选中
            const selectionData = this.$refs.agencyTable.selection
            for (let j = 0; j < selectionData.length; j++) {
              if (selectionData[j].id !== row[i].id) {
                this.$refs.agencyTable.toggleRowSelection(
                  selectionData[j],
                  false
                )
              }
            }
          }
        }
      }
      return
    },
    // 单位表格选中数据
    handleAgencySelectionChange(val) {
      const array = []
      // 获取表格选中数据,放到数组中缓存
      const selectionData = this.$refs.agencyTable.selection
      for (let i = 0; i < val.length; i++) {
        if (selectionData[0].id === val[i].id) {
          array.push(val[i])
        }
      }
      this.agencySelectData = array
      // 获取单位现有的工资项
      if (val.length > 0) {
        this.query.agencyId = val[0].id
        this.queryAgencySalaryInfoByAgencyId()
      } else {
        // 当单位表格取消选中时，将工资项表格选中状态清空
        this.$refs.salaryTable.clearSelection()
      }
    },
    // 工资项表格选中数据
    handleSalarySelectionChange(val) {
      this.salarySelectData = val
    },
    // 根据单位id查询已挂接的工资项
    queryAgencySalaryInfoByAgencyId() {
      queryAgencySalaryInfoByAgencyId(this.query).then(respose => {
        // 如果有挂接，将已挂接的工资项选中
        if (respose.data.length > 0) {
          respose.data.forEach(val => {
            this.salaryData.forEach(row => {
              if (val.salaryId === row.id) {
                this.$refs.salaryTable.toggleRowSelection(row, true)
                return
              }
            })
          })
        }
      })
    },
    selectable(row) {
      // 实发项和应发项复选框disable，不允许修改
      if (
        row.salaryCode === 's1' ||
        row.salaryCode === 's2'
      ) {
        return false
      } else {
        return true
      }
    },
    // 保存
    saveData() {
      if (this.agencySelectData.length === 0) {
        this.$message({
          showClose: true,
          message: '请选择单位',
          type: 'warning',
          duration: 4000
        })
        return
      }
      if (this.salarySelectData.length === 0) {
        this.$message({
          showClose: true,
          message: '请选择工资项',
          type: 'warning',
          duration: 4000
        })
        return
      }
      var data = {}
      data['agency'] = this.agencySelectData
      data['salary'] = this.salarySelectData
      data['flag'] = 'agency'
      saveAgencySalary(data).then(response => {
        this.$message({
          showClose: true,
          message: '保存成功',
          type: 'success',
          duration: 4000
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
@import "~@/styles/border.scss"; /*引入公共样式*/
.el-table {
  margin-top: 5px;
  ::v-deep .disabledCheck {
    .cell {
      .el-checkbox {
        .el-checkbox__input {
          display: none !important;
        }
      }
    }
  }
}
</style>
